<?php
/**
*    Images Saler - Component
*    Author : hm_advert@ymail.com
*    
**/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.client.helper');
jimport('joomla.application.component.model');
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . "libs" . DS . "functions.php");

class EcommerceModelProduct extends JModel
{
	
	var $_id = null;
	var $_table = '#__pr_product';
	var $_lists = '';
	var $_data = null;
	var $_params = NULL;
	
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->_params = &JComponentHelper::getParams( 'com_ecommerce' );
	}

	function setId($id)
	{
		$this->_id		= $id;
	}
	
	function getParams(){
		return $this->_params;
	}
	
	function getPrice($product_id){
		$query = '	SELECT id  
					FROM #__pr_product_category 						
					WHERE product_id = '.$product_id.' LIMIT 1';
		$this->_db->setQuery( $query );		
		$product_category_id = $this->_db->loadResult();
		$query = ' SELECT price  
					FROM #__pr_productdetail 
					WHERE product_category_id = ' . $product_category_id . ' ORDER BY producttype_id ASC';	
		$this->_db->setQuery( $query );		
		$price = $this->_db->loadObjectList();
		return $price;
	}
	
	function getPriceByCatid($product_id, $catid){
		$query = '	SELECT id  
					FROM #__pr_product_category 						
					WHERE product_id = '.$product_id.' AND category_id = '.$catid;
		$this->_db->setQuery( $query );		
		$product_category_id = $this->_db->loadResult();
		
		$query = ' SELECT price  
					FROM #__pr_productdetail 
					WHERE product_category_id = ' . $product_category_id . ' AND producttype_id = 1';
		$this->_db->setQuery( $query );		
		$price[0] = $this->_db->loadResult();
		
		$query = ' SELECT price  
					FROM #__pr_productdetail 
					WHERE product_category_id = ' . $product_category_id . ' AND producttype_id = 2';	
		$this->_db->setQuery( $query );		
		$price[1] = $this->_db->loadResult();
		$query = ' SELECT price  
					FROM #__pr_productdetail 
					WHERE product_category_id = ' . $product_category_id . ' AND producttype_id = 3';	
		$this->_db->setQuery( $query );		
		$price[2] = $this->_db->loadResult();
		
		return $price;
	}

	function &getData()
	{
	//die('aaa');

		if (empty( $this->_data )) 
		{
			$query = '	SELECT * 
						FROM #__pr_product 						
						WHERE id = '.$this->_id;
				
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();	
			if(trim($this->_data->related)!=""){
				$query = ' SELECT id, name FROM #__pr_product '.
						'  WHERE id  in ('.$this->_data->related.')'; 
				$this->_db->setQuery( $query );	
				
				$this->_data->related = $this->_db->loadObjectList();
			}
			else $this->_data->related=NULL;
		}

		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->number = null;
			$this->_data->name = null;
			$this->_data->type = null;
			$this->_data->unit = null;
			$this->_data->manufacturer= null;
			$this->_data->parcel = null;
			$this->_data->ingredient = null;
			$this->_data->origin = null;
			$this->_data->country = null;
			$this->_data->price = null;
			$this->_data->image = null;
			$this->_data->basic_info = null;
			$this->_data->instruction = null;
			$this->_data->description = null;
			$this->_data->allergen = null;
			$this->_data->expiry = null;
			$this->_data->quantity = null;
			$this->_data->ordering = null;
			$this->_data->published = null;
			
		}
			//var_dump($this->_data);die;
		return $this->_data;
	
	}
	
	

	function store()	{

		global $mainframe;
		$row =& $this->getTable();

		if(!$row->bind(JRequest::get('post'))){
		
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>\n';
			exit();
			
		}
		//all these lines are used to avoid lost data form post
		
		$id = JRequest::getVar('id');
		//var_dump($id);die;
		$number = JRequest::getVar('number');
		$name = JRequest::getVar('name');
		$price0 = doubleval(JRequest::getVar('price0'));
		$price1 = doubleval(JRequest::getVar('price1'));
		$price2 = doubleval(JRequest::getVar('price2'));	
		$iarray = array($price0, $price1, $price2);		
		$arrCat = JRequest::getVar('cat_id');
		//print_r($arrCat[0]);die;
		$ordering = intval(JRequest::getVar('ordering'));
		$published = intval(JRequest::getVar('published'));

		$row->number = JRequest::getVar('number');
		$row->name = JRequest::getVar('name');
		$row->quantity = intval(JRequest::getVar('quantity'));
		//$arrCat = JRequest::getVar('cat_id');	
		$row->unit= JRequest::getVar('unit');
		$row->parcel= JRequest::getVar('parcel');
		$row->origin= JRequest::getVar('origin');
		$row->expiry= JRequest::getVar('expiry');
		$row->country= JRequest::getVar('country');
		
		$row->description  = JRequest::getVar('description','','post','string',JREQUEST_ALLOWRAW);
		$row->ingredient  = JRequest::getVar('ingredient','','post','string',JREQUEST_ALLOWRAW);
		$row->basic_info  = JRequest::getVar('basic_info','','post','string',JREQUEST_ALLOWRAW);
		$row->instruction  = JRequest::getVar('instruction','','post','string',JREQUEST_ALLOWRAW);
		$row->allergen  = JRequest::getVar('allergen','','post','string',JREQUEST_ALLOWRAW);
		

		
		//$row->ordering = intval(JRequest::getVar('ordering'));

		//print_r($row->id);die;
		//$row->ordering = intval(JRequest::getVar('ordering'));
		//var_dump($ordering);die;
		$row->published = intval(JRequest::getVar('published'));
		
		/*if($_FILES['txtimage']['name']){
		
			$rand_image = mt_rand();
			$row->image = $rand_image.$_FILES['txtimage']['name'];
		} else {
			$row->image = JRequest::getVar('image');
		}*/
				
		//$row->alias = JFilterOutput::stringURLSafe($row->name);
		//print_r($row);exit;
		$query = "SELECT id FROM #__pr_producttype";
		$this->_db->SetQuery($query);
		$itype = $this->_db->loadResultArray();	
		if(!$row->store()){
			echo '<script>alert("'.$row->getError().'");window.history.go(-1);</script>\n';
			exit();
		}
		
		else
		{
			if($id==0){
				for($m=0; $m<count($arrCat); $m++){				
							$query = "INSERT INTO #__pr_product_category(category_id, product_id) VALUES (".$arrCat[$m].", ".$row->id.")";
							$this->_db->setQuery($query); 
							$this->_db->query();																		
					}					
					
				
				$query = "SELECT id FROM #__pr_product_category WHERE product_id=".$row->id;
				$this->_db->SetQuery($query);
				$icat = $this->_db->loadResultArray();		
				for($i=0; $i<count($arrCat); $i++){	
					for($j=0; $j<count($itype) ;$j++){			
						$query = "INSERT INTO #__pr_productdetail(product_category_id, producttype_id, price) VALUES (".$icat[$i].", ".$itype[$j][0].", ".$iarray[$j].")";
						$this->_db->setQuery($query); 
						$this->_db->query();	

					}			
				}				
			}			
			else{						
				$product_id = $row->id;
				$arr_price = $iarray;

				$this->_db->setQuery("START TRANSACTION");
				$this->_db->query();
				$query = "SELECT id FROM #__pr_product_category WHERE product_id =".$product_id;				
				$this->_db->SetQuery($query);
				$arr_product_category = $this->_db->loadAssocList();

	
				$query = "DELETE FROM #__pr_product_category WHERE product_id=".$product_id ;
				//echo $query . "<br />";
				$this->_db->SetQuery($query);
				$result1 = $this->_db->query();
				
				$str = "";
				foreach($arr_product_category as $pc=>$valpc){
					$str = $str . $valpc["id"] . ",";

				}

				$str = trim($str,",");
				$str .= "";
				$query = "DELETE FROM #__pr_productdetail WHERE product_category_id in (".$str.")";
				//echo $query . "<br />";
				$this->_db->SetQuery($query);
				$result2 = $this->_db->query();
				
				for($i=0; $i<count($arrCat); $i++){	
					$query = "INSERT INTO #__pr_product_category (`category_id`, `product_id`) VALUES(".$arrCat[$i].", ".$product_id.")";
					//echo $query . "<br />";
					$this->_db->SetQuery($query);
					$result3 = $this->_db->query();
					if(!$result3){
						break;
					}
					$product_category_id = $this->_db->insertid();
					
					for($j=0; $j<count($itype) ;$j++){			
						$query = "INSERT INTO #__pr_productdetail(product_category_id, producttype_id, price) VALUES (".$product_category_id.", ".$itype[$j][0].", ".$arr_price[$j].")";
						//echo $query . "<br />";

						$this->_db->setQuery($query); 
						$result4 = $this->_db->query();	
						if(!$result4){
							break;							
						}
					}	
					
				}
				if($result1 && $result2 && $result3 && $result4)
				{
					$this->_db->setQuery("COMMIT");
					//echo "OK";
					$this->_db->query();
					
				}
				else
				{
				
					//echo "NOT OK";
					$this->_db->setQuery("ROLLBACK");
					$this->_db->query();
				}
				
				//exit;
				//return true;
			}

		}
	}

	function delete()
	{
		global $mainframe;
		$cid = JRequest::getVar('cid',array(),'','array');
		$db = JFactory::getDBO();
		if(count($cid)> 0 )
		{
			$cids = implode(',',$cid);
			//print_r($cids);die;
			$query = "select * from #__pr_product where id in ($cids)";
			$db->setQuery($query);
			$row = $db->loadObjectList();
						
		/*	foreach ($row as $_file)
			{
				$prodir = "../components/com_ecommerce/imgupload/";
				if(file_exists($prodir . $_file->image))
				{
					unlink($prodir . $_file->image);
				}
			}*/

			$query1 = "DELETE FROM #__pr_product WHERE id IN (".$cids.")";				
			$db->SetQuery($query1);
			$db->query();
	
			$query2 = "SELECT id FROM #__pr_product_category WHERE product_id in (".$cids.")";				
			$db->SetQuery($query2);

			$arr_product_category = $this->_db->loadAssocList();
			$query3 = "DELETE FROM #__pr_product_category WHERE product_id in (".$cids.")";
			$db->SetQuery($query3);
			$db->query();			
			$str = "";
			foreach($arr_product_category as $pc=>$valpc){
				$str = $str . $valpc["id"] . ",";
			}
			$str = trim($str,",");
			$str .= "";

			$query4 = "DELETE FROM #__pr_productdetail WHERE product_category_id in (".$str.")";
			$db->SetQuery($query4);
			$db->query();
			

			if(!$db->query())
			{
				echo "<script> alert('".$db->getErrorMsg()."');window.history.go(-1); </script>\n";
			}
		}

		return true;
	}

	function publish($publish) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Publish' : 'Unpublish';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET published = '.(int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}
	
	function setPromotion($promotion) {
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		JArrayHelper::toInteger($cid);
	
		if ( count( $cid ) < 1 ) {
			$action = $publish ? 'Promotion' : 'UnPromotion';
			JError::raiseError(500, JText::_( 'Select Item to '.$action, true ) );
		}
		
		$cids = implode( ',', $cid );
		$count = count( $cid );
		$query = 'UPDATE #__pr_product'
		. ' SET promotion = '.(int) $promotion
		. ' WHERE id IN ( '.$cids.' )'
		;

		$db =& JFactory::getDBO();
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}
	
	}

	function orderSection( $uid, $inc)
	{
		$row =& $this->getTable();
		$row->load( $uid );
		$row->move( $inc);
	}

	function saveOrder( &$cid )
	{
		$row =& $this->getTable();
	
		$total		= count( $cid );
		$order		= JRequest::getVar( 'order', array(0), 'post', 'array' );
		JArrayHelper::toInteger($order, array(0));
	
		// update ordering values
		for( $i=0; $i < $total; $i++ )
		{
			$row->load( (int) $cid[$i] );
			if ($row->ordering != $order[$i]) {
				$row->ordering = $order[$i];
				if (!$row->store()) {
					JError::raiseError(500, $db->getErrorMsg() );
				}
			}
		}
	
		$row->reorder();
	}


}

?>